package com.uroad.liaoningpos.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.GlobalData;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.model.BeondutyMDL;
import com.uroad.liaoningpos.model.OnlineMDL;
import com.uroad.liaoningpos.model.UserMDL;
import com.uroad.liaoningpos.util.ImeiUtil;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.check.CheckPermissionUtil;
import com.uroad.lib.util.encrypt.SecurityUtil;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.widget.ClearEditText;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 15:35
 * @描述 登录页
 */
public class LoginActivity extends BaseActivity {
    private static final int REQUEST_NAME_CODE = 10001;
    private static final int REQUEST_BEONDUTY_CODE = 10002;
    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.tvBeondutyName)
    TextView      tvBeondutyName;
    @BindView(R.id.tvStoreName)
    TextView      tvStoreName;
    @BindView(R.id.tvStoreNo)
    TextView      tvStoreNo;
    @BindView(R.id.etUserName)
    ClearEditText etUserName;
    @BindView(R.id.etPwd)
    ClearEditText etPwd;
    @BindView(R.id.tvMerchantNo)
    TextView tvMerchantNo;
    @BindView(R.id.tvMerchantNozl)
    TextView tvMerchantNozl;
    @BindView(R.id.tvTerminalNo)
    TextView tvTerminalNo;
    @BindView(R.id.tvTerminalNozl)
    TextView tvTerminalNozl;
    @BindView(R.id.btnLogin)
    Button        btnLogin;
    private String                    deviceuuid;
    private String                    deviceversion;
    private String                    devicemodel;
    private String                    deviceName;
    private String                    appname;
    private String                    appversion;
    private String                    imei;
    private List<OnlineMDL.StoreInfo> list;
    private String                    merchantshopid;//商户id
    private String                    beonduty = "";//班次
    private String                    username;
    private int count = 0;
    private long oldTime = System.currentTimeMillis();
    private long curTime = 0;
    private List<BeondutyMDL> beondutys;
    private String merchantno = "";
    private String merchantnozhilian = "";
    private String terminalno = "";
    private String merchantname = "";
    private String terminalnozhilian = "";
    private String merchantnamezhilian = "";
    private boolean isCanToMain = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayoutWithoutTitle(R.layout.activity_login);
        ButterKnife.bind(this);
        //检查权限
        checkDevicePermission();
        initData();
        getBeonduty();
        bindInfoService();
        SignIn();
    }

    private void initData() {
        merchantno = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO, "");
        merchantnozhilian = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO_ZHILIAN, "");
        terminalno = (String) SPUtils.get(this, SPContants.SP_TERMINALNO, "");
        terminalnozhilian = (String) SPUtils.get(this, SPContants.SP_TERMINALNO_ZHILIAN, "");
        merchantname = (String) SPUtils.get(this, SPContants.SP_MERCHANTNAME, "");
        tvMerchantNo.setText("间连商户号：" + merchantno);
        tvMerchantNozl.setText("直连商户号：" + merchantnozhilian);
        tvTerminalNo.setText("间连终端号：" + terminalno);
        tvTerminalNozl.setText("直连终端号：" + terminalnozhilian);

    }

    @Override
    protected void bindInfoServiceSuccess() {
        super.bindInfoServiceSuccess();
        try {
            merchantno = infoService.getParam(GlobalData.PARAMS_KEY_BASE_MERCHANTID);
            terminalno = infoService.getParam(GlobalData.PARAMS_KEY_BASE_POSID);
            merchantname = infoService.getParam(GlobalData.PARAMS_KEY_BASE_MERCHANTNAME);
            if (!TextUtils.isEmpty(merchantno)) {
                tvMerchantNo.setText("间连商户号：" + merchantno);
                SPUtils.put(this, SPContants.SP_MERCHANTNO,merchantno);
            }
            if (!TextUtils.isEmpty(merchantnozhilian)) {
                tvMerchantNozl.setText("直连商户号：" + merchantnozhilian);
                SPUtils.put(this, SPContants.SP_MERCHANTNO,merchantnozhilian);
            }
            if (!TextUtils.isEmpty(terminalno)) {
                tvTerminalNo.setText("间连终端号：" + terminalno);
                SPUtils.put(this, SPContants.SP_TERMINALNO, terminalno);
            }
            if (!TextUtils.isEmpty(terminalnozhilian)) {
                tvTerminalNozl.setText("直连终端号：" + terminalnozhilian);
                SPUtils.put(this, SPContants.SP_TERMINALNO, terminalnozhilian);
            }
            if (!TextUtils.isEmpty(merchantname)) {
                SPUtils.put(this, SPContants.SP_MERCHANTNAME, merchantname);
            }
            if (isCanToMain) {
                openActivity(MainActivity.class);
                finish();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void getBeonduty() {
        doRequest(PosWS.getbeonduty, PosWS.getbeondutyParams(), PosWS.getbeonduty);
    }

    private void checkDevicePermission() {
        CheckPermissionUtil checkPermissionUtil = new CheckPermissionUtil(this, new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, new CheckPermissionUtil.CheckPermissionCallBack() {
            @Override
            public void permissionAllow() {
                //获取权限成功
                getDeviceInfo();
                online();
            }

            @Override
            public void permissionRefuse() {
                //获取权限失败
                LogUtil.i("LoginActivity", "权限被拒绝");
            }
        });
        checkPermissionUtil.checkPermissions();
    }

    public boolean getDeviceInfo() {
        try {
            deviceuuid = ImeiUtil.getMyImei(this);//六合一信息
            SPUtils.put(this, SPContants.SP_DEVICEUUID, deviceuuid);
            imei = android.os.Build.SERIAL;
            SPUtils.put(this, SPContants.SP_IMEI, imei);
            deviceversion = Build.VERSION.RELEASE;//安卓版本
            devicemodel = Build.MODEL;//手机型号
            BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
            if (myDevice != null) {
                deviceName = myDevice.getName();
            } else {
                deviceName = devicemodel;
            }
            appname = getResources().getString(R.string.app_name); //app名称

            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            appversion = info.versionName; //app版本
            SPUtils.put(this, SPContants.SP_APPVERSION, appversion);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private void online() {
        DialogHelper.showLoading(this, "正在获取商户信息");
        doRequest(PosWS.online,
                PosWS.onlineParams(deviceversion, devicemodel, appversion, deviceuuid, deviceName, imei),
                PosWS.online);
    }


    @OnClick({R.id.btnLogin, R.id.tvStoreName, R.id.tvBeondutyName, R.id.ivLogo})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                if (TextUtils.isEmpty(merchantshopid)) {
                    showShortToast("请选择商户名称");
                    return;
                }
                if (TextUtils.isEmpty(beonduty)) {
                    showShortToast("请选择班次");
                    return;
                }

                username = etUserName.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                if (TextUtils.isEmpty(username)) {
                    showShortToast("请输入登录账号");
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    showShortToast("请输入登录密码");
                    return;
                }
                try {
                    pwd = SecurityUtil.EncoderByMd5(pwd);
                    login(username,pwd);
                } catch (Exception e) {
                    e.printStackTrace();
                    showShortToast("系统繁忙，请稍后重试");
                }
                break;
            case R.id.tvBeondutyName:
                if (beondutys != null && beondutys.size() > 0) {
                    Intent intent = new Intent(this, SelectBeondutyInfoActivity.class);
                    intent.putExtra("type", "name");
                    intent.putExtra("list", (Serializable) beondutys);
                    startActivityForResult(intent, REQUEST_BEONDUTY_CODE);
                }
                break;
            case R.id.tvStoreName:
                if (list != null && list.size() > 0) {
                    Intent intent = new Intent(this, SelectStoreInfoActivity.class);
                    intent.putExtra("type", "name");
                    intent.putExtra("list", (Serializable) list);
                    startActivityForResult(intent, REQUEST_NAME_CODE);
                }
                break;
            case R.id.tvStoreNo:
                if (TextUtils.isEmpty(merchantshopid)) {
                    showShortToast("请选择商户名称");
                }
                break;
            case R.id.ivLogo:
                curTime = System.currentTimeMillis();
                if (curTime - oldTime < 1000) {
                    count ++;
                    if (count >= 4) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //直接进入手机中的wifi网络设置界面
                        //				startActivity(new Intent(Settings.ACTION_SETTINGS)); //直接进入手机中设置界面
                    }
                }else{
                    count = 0;
                }
                oldTime = curTime;
                break;
        }
    }

    //签到
    private void SignIn(){
        String str = "payment://com.newland.pospp/login?channelId=boc";

        Uri uri = Uri.parse(str);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivityForResult(intent, 1);

        String str1 = "payment://com.newland.pospp/login?channelId=directscan";

        Uri uri1 = Uri.parse(str1);
        Intent intent1 = new Intent(Intent.ACTION_VIEW, uri1);
        startActivityForResult(intent1, 2);
        /*Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.yada.spos.cashierplatfrom",
                "com.yada.spos.cashierplatfrom.InvokeActivity"));
        intent.putExtra("channelName", "cardPay");
        intent.putExtra("tranType", "1");
        startActivityForResult(intent, 0);*/
    }

    //登录
    private void login(String username, String pwd) {
        DialogHelper.showLoading(this,"正在登录");
        doRequest(PosWS.login, PosWS.loginParams(username, pwd, deviceuuid, merchantshopid, beonduty, imei), PosWS.login);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_NAME_CODE == requestCode) {
            OnlineMDL.StoreInfo mdl = (OnlineMDL.StoreInfo) data.getSerializableExtra("result");
            if (mdl != null) {
                merchantshopid = mdl.getMerchantshopid();
                tvStoreName.setText(mdl.getShopname());
                tvStoreNo.setText(mdl.getMerchantshopid());
            }
        } else if (REQUEST_BEONDUTY_CODE == requestCode) {
            BeondutyMDL mdl = (BeondutyMDL) data.getSerializableExtra("result");
            if (mdl != null) {
                beonduty = mdl.getBeonduty();
                tvBeondutyName.setText(beonduty);
            }
        } else if(1 == requestCode){
            merchantno = data.getStringExtra( "merchantId");
            terminalno = data.getStringExtra( "terminalId");
            merchantname = data.getStringExtra( "merchantName");
            String batchNo = data.getStringExtra( "batchNo");

            /*try {
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_MERCHANTID,merchantno);
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_POSID, terminalno);
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_MERCHANTNAME, merchantname);
            } catch (RemoteException e) {
                e.printStackTrace();
            }*/
            if (!TextUtils.isEmpty(merchantno)) {
                tvMerchantNo.setText("间连商户号：" + merchantno);
                SPUtils.put(this, SPContants.SP_MERCHANTNO,merchantno);
            }
            if (!TextUtils.isEmpty(terminalno)) {
                tvTerminalNo.setText("间连终端号：" + terminalno);
                SPUtils.put(this, SPContants.SP_TERMINALNO, terminalno);
            }
            if (!TextUtils.isEmpty(merchantname)) {
                SPUtils.put(this, SPContants.SP_MERCHANTNAME, merchantname);
            }
            if (isCanToMain) {
                openActivity(MainActivity.class);
                finish();
            }
        }else if(2 == requestCode){
            merchantnozhilian = data.getStringExtra( "merchantId");
            terminalnozhilian = data.getStringExtra( "terminalId");
            merchantname = data.getStringExtra( "merchantName");
            String batchNo = data.getStringExtra( "batchNo");

            /*try {
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_MERCHANTID,merchantno);
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_POSID, terminalno);
                infoService.setParam(GlobalData.PARAMS_KEY_BASE_MERCHANTNAME, merchantname);
            } catch (RemoteException e) {
                e.printStackTrace();
            }*/
            if (!TextUtils.isEmpty(merchantnozhilian)) {
                tvMerchantNozl.setText("直连商户号："+merchantnozhilian);
                SPUtils.put(this, SPContants.SP_MERCHANTNO_ZHILIAN,merchantnozhilian);
            }
            if (!TextUtils.isEmpty(terminalnozhilian)) {
                tvTerminalNozl.setText("直连终端号："+terminalnozhilian);
                SPUtils.put(this, SPContants.SP_TERMINALNO_ZHILIAN, terminalnozhilian);
            }
//            if (!TextUtils.isEmpty(merchantname)) {
//                SPUtils.put(this, SPContants.SP_MERCHANTNAME, merchantname);
//            }
            if (isCanToMain) {
                openActivity(MainActivity.class);
                finish();
            }
        }
    }


    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        DialogHelper.endLoading();
        JSONObject jsonObject = JSON.parseObject(result);
        if (FastJsonUtils.getJsonStatu00(jsonObject)) {
            if (PosWS.online.equals(id)) {
                //商户信息
                OnlineMDL mdl = FastJsonUtils.parseDataObjectJSON(jsonObject, OnlineMDL.class);
                if (mdl != null && !TextUtils.isEmpty(mdl.getTicketid())) {
                    String beonduty = mdl.getBeonduty();
                    if (!"".equals(beonduty)&&beonduty != null) {
                        list = mdl.getList();
                    }
                    if (!TextUtils.isEmpty(mdl.getTicketid()) && !TextUtils.isEmpty(mdl.getBeonduty())) {
                        SPUtils.put(this, SPContants.SP_TICKETID, mdl.getTicketid());
                        SPUtils.put(this, SPContants.SP_BEONDUTY, mdl.getBeonduty());
                        String name = (String) SPUtils.get(this, SPContants.SP_USERNAME, "");
                        if (!TextUtils.isEmpty(name))
                            isCanToMain = true;
                        if (!TextUtils.isEmpty(merchantno)&&!TextUtils.isEmpty(name)) {
                            openActivity(MainActivity.class);
                            finish();
                        }
                    }
                }else{
                    list = mdl.getList();
                }
            } else if (PosWS.getbeonduty.equalsIgnoreCase(id)) {
                beondutys = FastJsonUtils.parseDataArrayJSON(jsonObject, BeondutyMDL.class);
            } else if (PosWS.login.equalsIgnoreCase(id)) {
                UserMDL userMDL = FastJsonUtils.parseDataObjectJSON(jsonObject, UserMDL.class);
                if (userMDL != null) {
                    SPUtils.put(this, SPContants.SP_TICKETID, userMDL.getTicketid());
                    SPUtils.put(this, SPContants.SP_USERUUID, userMDL.getUseruuid());
                    SPUtils.put(this, SPContants.SP_MERCHANTSHOPID, userMDL.getMerchantshopid());
                    SPUtils.put(this, SPContants.SP_POSMERCHANTNO, userMDL.getPosmerchantno());
                    SPUtils.put(this, SPContants.SP_SHOPNAME, userMDL.getShopname());
                    SPUtils.put(this, SPContants.SP_USERNAME, userMDL.getUsername());
                    SPUtils.put(this, SPContants.SP_BEONDUTY, beonduty);
                    showShortToast("登录成功");
                    openActivity(MainActivity.class);
                    finish();
                }
            }
        } else {
            Toast.makeText(this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        DialogHelper.endLoading();
        showShortToast("系统繁忙，请稍后重试");
    }

    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        DialogHelper.endLoading();
        showShortToast("系统繁忙，请稍后重试");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
